package com.lzp.java.concurrent.threadcore.threadandobject.object;

/**
 * notifyAll的使用
 * 1. notifyAll唤醒加锁对象上的所有线程
 * 2. 唤醒后的执行顺序，与线程的start顺序无关
 *
 * @author lzp
 * @date 2020/02/05
 */
public class WaitNotifyAll implements Runnable {
    // 资源--要锁定的对象
    private static final Object resourceA = new Object();

    public static void main(String[] args) {
        Runnable task = new WaitNotifyAll();
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        thread1.start();
        thread2.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println(Thread.currentThread().getName() + "唤醒等待resourceA的所有线程");
                    resourceA.notifyAll();
                }
            }
        });
        thread3.start();
    }

    @Override
    public void run() {
        synchronized (resourceA) {
            System.out.println(Thread.currentThread().getName() + "获取到锁");
            try {
                System.out.println(Thread.currentThread().getName() + "进入WAITING状态，放弃resourceA的monitor锁");
                resourceA.wait();
                System.out.println(Thread.currentThread().getName() + "重新获取到resourceA的monitor锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
